<form lay-filter="receiptForm" id="receiptForm" class="layui-form open-form">
  <div class="open-model" id="receiptFormContent">
    <div class="open-auto">
      <input name="id" type="hidden" />
      <div class="layui-row">
        <table class="layui-table" id="nowValTable" lay-filter="nowValTable"></table>
      </div>
      <div class="layui-row">
        <table class="layui-table" id="receiptFormTable" lay-filter="receiptFormTable"></table>
      </div>
      <div class="layui-form-item text-right">
        <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
        <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
      </div>
    </div>
  </div>
</form>
<script>
  layui.use(['layer', 'form', 'table', 'admin', 'laydate', 'upload', 'laytpl'], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    const nowData = { ...parentData };
    const data = nowData.data;
    if (['recList'].includes(nowData.eventName)) {
      admin.setFormDisable('#receiptForm', true);
    }
    const receiptTypeRes = await admin.reqPro('enterprise/dict/admin/dictLabel/select', { dictType: 'bill_receipt_type' });
    const receiptTypeList = receiptTypeRes.data;
    console.log(
      'receiptTypeList',
      receiptTypeList.map((v) => {
        return {
          label: v.labelName,
          value: v.labelValue,
        };
      }),
    );
    table.render({
      elem: '#nowValTable',
      data: [],
      page: false,
      cellMinWidth: 100,
      cols: [
        [
          { field: 'code', align: 'center', title: '账单编码' },
          { field: 'supplierName', align: 'center', title: '供应商名称' },
          { field: 'billStartTime', align: 'center', title: '账单开始时间' },
          { field: 'billEndTime', align: 'center', title: '账单结束时间' },
          { field: 'signOrderNum', align: 'center', title: '签收单数' },
          { field: 'billSum', align: 'center', title: '账单总金额' },
          {
            field: 'billSum',
            align: 'center',
            title: '账单剩余结算余额',
            templet: (d) => {
              return d.billSum - data.settleList.reduce((total, item) => total + Number(item.paySum), 0);
            },
          },
          { field: 'settleStatus', align: 'center', title: '结算状态' },
          { field: 'receiptStatus', align: 'center', title: '发票状态' },
          { field: 'createTime', align: 'center', title: '生成时间' },
        ],
      ],
      done: function () {},
    });
    table.render({
      elem: '#receiptFormTable',
      data: [],
      page: false,
      cellMinWidth: 100,
      cols: [
        [
          {
            field: 'receiptType',
            align: 'center',
            title: '发票类型',
            templet: admin.setTableSelect(
              'receiptType',
              receiptTypeList.map((v) => {
                return {
                  label: v.labelName,
                  value: v.labelValue,
                };
              }),
              nowData.eventName === 'recList',
            ),
          },
          {
            field: 'receiptCode',
            align: 'center',
            title: '发票编号',
            templet: admin.setTableInput('receiptCode', nowData.eventName === 'recList'),
          },
          {
            field: 'receiptSum',
            align: 'center',
            title: '开票金额',
            templet: admin.setTableInput('receiptSum', nowData.eventName === 'recList'),
          },
          {
            field: 'remark',
            align: 'center',
            title: '备注',
            templet: admin.setTableInput('remark', nowData.eventName === 'recList'),
          },
          {
            field: 'receiptTime',
            align: 'center',
            title: '开票日期',
            templet: admin.setTableInput('receiptTime', nowData.eventName === 'recList', 'receiptTime'),
          },
          {
            align: 'center',
            title: '凭证',
            templet: admin.setTableUpload('receiptImg', nowData.eventName === 'recList', 'receiptTime'),
          },
        ],
      ],
      done: function () {
        $('.layui-table-body').css('overflow', 'visible');
        $('.layui-table-box').css('overflow', 'visible');
        $('.layui-table-view').css('overflow', 'visible');
        admin.tableInputChange('receiptFormTable');
        upload.render({
          elem: '.upload-btn', // 绑定上传按钮
          url: config.upload_url + 'uploadFile',
          accept: 'file', // 可接受的文件类型
          headers: { Authorization: 'Bearer ' + config.getToken() },
          done: function (res, index, upload) {
            // 上传成功的回调
            if (res.code === 200) {
              // 更新表格缓存中的数据
              const button = $(this.item);
              const index = button.data('index');
              let tableData = table.cache['receiptFormTable'];
              let rowIndex = tableData.findIndex((v) => v['LAY_TABLE_INDEX'] == index);
              if (rowIndex > -1) {
                tableData[rowIndex].receiptImg = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
              }
              $(`#uploaded-${index}`).html(`<a href="${res.data.url}" target="_blank">查看附件</a>`);
              console.log('文件上传成功:', res.data);
            } else {
              console.error('文件上传失败:', res.message);
            }
          },
          error: function () {
            // 上传失败的回调
            console.error('上传失败');
          },
        });
        const inputs = document.querySelectorAll('.receiptTime');
        inputs.forEach((input, index) => {
          laydate.render({
            elem: input,
            format: 'yyyy-MM-dd',
            trigger: 'click',
            done: function (value) {
              input.value = value;
              let tableData = table.cache['receiptFormTable'];
              let rowIndex = tableData.findIndex((v) => v['LAY_TABLE_INDEX'] == index);
              if (rowIndex > -1) {
                tableData[rowIndex].receiptTime = value;
              }
            },
          });
        });
      },
    });
    if (data && data.id) {
      table.reload('nowValTable', {
        data: [data],
      });
      if (nowData.eventName === 'recList') {
        console.log('data.receiptList', data.receiptList);
        table.reload('receiptFormTable', {
          data: [...data.receiptList],
        });
      } else if (nowData.eventName === 'receipt') {
        table.reload('receiptFormTable', {
          data: [
            {
              billId: data.id,
            },
          ],
        });
      }
    }

    $('#Configure').click(function () {});
    form.on('submit(formSubmit)', function (d) {
      const formData = [...table.cache['receiptFormTable']][0];
      console.log(formData);
      admin.req(
        'enterprise/purchase/admin/purchaseBillReceipt/add',
        JSON.stringify(formData),
        function (res) {
          layer.closeAll('loading');
          if (res.code === 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload('billTable');
            layer.closeAll('page');
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        'POST',
        false,
        'application/json',
      );
      return false;
    });
  });
</script>

<style>
  #receiptForm .layui-form-label {
    width: 120px;
  }

  #receiptForm .layui-input-block {
    margin-left: 150px;
  }

  #receiptForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
  #receiptForm .layui-table-cell {
    overflow: visible !important;
  }
</style>
